from django.contrib import admin
# Register your models here.
from django.forms import ModelForm
from django.utils.safestring import mark_safe
from django.contrib.admin.widgets import AdminFileWidget
from apps.models import Carousel, Nav, News, Jobs, ProductTypes, Product, \
    FileDown, LeaveMessage, SubTitle, SysConfig, Images, NavUrls, NavImages, Honor, CompanyImage, Case



class AdminImageWidget(AdminFileWidget):
    ''' 图片预览
    '''
    def render(self, name, value, attrs=None):
        output = []
        if value and getattr(value, "url", None):
            image_url = value.url
            file_name = str(value)
            output.append('<a href="%s" target="_blank"><img src="%s" alt="%s"   height="200" width="200" /></a>' % (image_url, image_url, file_name))
        output.append(super(AdminFileWidget, self).render(name, value, attrs))
        return mark_safe(''.join(output))

class CarouselAdminForm(ModelForm):
    class Meta:
        fields = '__all__'
        widgets = {
            'img': AdminImageWidget(),
        }
        model = Carousel

class CarouselAdmin(admin.ModelAdmin):
    form = CarouselAdminForm

class NewsAdmin(admin.ModelAdmin):
    search_fields = ('nav', 'content', 'types', 'title')
    list_filter = ('nav', 'types', 'title')
    list_display = ('nav', 'types', 'title')
    readonly_fields = ('view_times',)


class NavAdmin(admin.ModelAdmin):
    search_fields = ('name',)
    list_display = ('name',)
    list_filter = ('name',)



from apps.models import Carousel, Nav, News, Jobs, ProductTypes, Product, \
    FileDown, LeaveMessage, SubTitle, SysConfig, Images


admin.site.register(News, NewsAdmin)
admin.site.register(Nav, NavAdmin)
admin.site.register(Carousel, CarouselAdmin)
admin.site.register(Jobs)
admin.site.register(ProductTypes)
admin.site.register(Product)
admin.site.register(FileDown)
admin.site.register(LeaveMessage)
admin.site.register(SubTitle)
admin.site.register(SysConfig)
admin.site.register(Images)
admin.site.register(NavUrls)
admin.site.register(NavImages)
admin.site.register(Honor)
admin.site.register(Case)
admin.site.register(CompanyImage)
